package com.hfzy.ihk.web.linkcall.controller.setting.knowledgeBase;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hfzy.ihk.common.constants.GlobalStatic;
import com.hfzy.ihk.common.util.Utils;
import com.hfzy.ihk.common.util.file.excel.ExcelUtils;
import com.hfzy.ihk.common.util.http.HttpClientUtils;
import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.common.web.WebResult;
import com.hfzy.ihk.facade.linkcall.entity.BusinessTypeBase;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingFlow;
import com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingPackage;
import com.hfzy.ihk.facade.linkcall.entity.knowledge.KnowledgeBase;
import com.hfzy.ihk.facade.linkcall.enums.*;
import com.hfzy.ihk.facade.linkcall.vo.KnowledgeBaseResultVo;
import com.hfzy.ihk.facade.linkcall.vo.knowledgeBase.KnowledgeBaseVo;
import com.hfzy.ihk.web.linkcall.support.annotation.PushMsgToAIService;
import com.hfzy.ihk.web.linkcall.support.annotation.ReceiveUserPrivParam;
import com.hfzy.ihk.web.linkcall.biz.BusinessTypeBaseBiz;
import com.hfzy.ihk.web.linkcall.biz.KnowledgeBase.KnowledgeBaseBiz;
import com.hfzy.ihk.web.linkcall.biz.KnowledgeBase.type.IndustryTypeBiz;
import com.hfzy.ihk.web.linkcall.biz.flow.config.SpeakingFlowBiz;
import com.hfzy.ihk.web.linkcall.biz.flow.config.SpeakingPackageBiz;
import com.hfzy.ihk.web.linkcall.support.DefaultResult;
import com.hfzy.ihk.web.linkcall.utils.IKSegmenterUtils;
import com.hfzy.ihk.web.linkcall.utils.LayUiParamUtils;
import com.hfzy.ihk.web.linkcall.utils.WebResultUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * 知识库
 */
@Controller
@RequestMapping("/knowledgeBase")
public class KnowledgeBaseController {


    Logger logger = LoggerFactory.getLogger(KnowledgeBaseController.class);


    @Autowired
    private KnowledgeBaseBiz knowledgeBaseBiz;

    @Autowired
    private SpeakingFlowBiz speakingFlowBiz;

    @Autowired
    private SpeakingPackageBiz speakingPackageBiz;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IndustryTypeBiz industryTypeBiz;

    @Autowired
    private BusinessTypeBaseBiz businessTypeBaseBiz;


    @Value("${aiService.knowledgebase.analysis.singleCall.url}")
    public String singleCallUrl;

    @Value("${aiService.knowledgebase.analysis.basicFunc.url}")
    public String basicFuncUrl;

    /**
     * 功能描述:
     *
     * @param: []
     * @return: 转跳到页面
     * @auther:
     * @date: 2018/8/7
     */
    @RequestMapping("queryKnowledgeBase")
    public String queryKnowledgeBase(Model model, String packageId,String affectType,String refPackageId,String createUserId,String canSearchAll) {
        try{
            List<SpeakingFlow> speakingFlowList = null;
            if (StringUtil.isNotNull(packageId)) {
                model.addAttribute("packageId", packageId);

                /*
                //关键字的检验
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append(",");
                Set<String> keywordSet = redisTemplate.opsForSet().members(packageId);
                Iterator<String> iterator = keywordSet.iterator();
                while (iterator.hasNext()) {
                    stringBuffer.append(iterator.next() + ",");
                }
                model.addAttribute("keywords", stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1));*/

                Map map = new HashMap();
                map.put("packageId",packageId);
                speakingFlowList = speakingFlowBiz.getSpeakingFlowList(map);
            }else{
                //查询到所有的SpeakingFlows,用于页面多轮会话的下拉框显示
                speakingFlowList = speakingFlowBiz.selectAll();
            }

            if (speakingFlowList != null && speakingFlowList.size() > 0) {
                model.addAttribute("speakingFlowList", speakingFlowList);
            }
            if(StringUtil.isNotNull(affectType)){
                model.addAttribute("affectType",affectType);
            }
/*Map params = new HashMap();
            params.put("packageId","0_node_3");
            List<KnowledgeBase> knowledgeBases = knowledgeBaseBiz.searchKnowledgeBaseByField(params);
            if(knowledgeBases!=null && !knowledgeBases.isEmpty()){
                knowledgeBases.forEach(it->{
                    knowledgeBaseBiz.delete(it);
                });
            }*/
            model.addAttribute("knowledgeTypes", KnowledgeType.values());
            if(Utils.isNullString(refPackageId))
                refPackageId = "";
            model.addAttribute("refPackageId", refPackageId);
            model.addAttribute("createUserId", createUserId!=null?createUserId:"0");
            model.addAttribute("canSearchAll", canSearchAll!=null?canSearchAll:"true");

            /*Set<String> members = redisTemplate.opsForSet().members(packageId);
            Iterator it1 = members.iterator();
            while(it1.hasNext()){
                redisTemplate.opsForSet().remove(packageId, it1.next());
            }*/
           /* List<KnowledgeBase> allK = knowledgeBaseBiz.selectAll();
            Map<String,List<KnowledgeBase>> gbKl = allK.stream().collect(Collectors.groupingBy(KnowledgeBase::getPackageId));
            //gbKl
            gbKl.entrySet().stream().forEach(it->{
                IndustryType industryType = industryTypeBiz.selectById(it.getKey());
                List<KnowledgeBase> knowledgeBases = it.getValue();
                if(industryType==null){
                    for(KnowledgeBase knowledgeBase:knowledgeBases){
                        knowledgeBase.setAffectType(AffectType.PRIVATE);
                    }
                }else{
                    for(KnowledgeBase knowledgeBase:knowledgeBases){
                        knowledgeBase.setAffectType(AffectType.COMMON);
                    }
                }
                knowledgeBaseBiz.updateBatchById(knowledgeBases);
            });*/
        }catch (Exception e){
            e.printStackTrace();
        }
        return "page/knowledgeBase/queryKnowledgeBase";
    }

//    @ReceiveUserPrivParam
    @RequestMapping("queryCommonKnowledgeBase")
    public String queryCommonKnowledgeBase(String packageId,Model model){
        /*if(!Utils.isNullString(packageId)){//根据packageId 获取到对应的 树状结构
            SpeakingPackage speakingPackage = speakingPackageBiz.getSpeakingPackageById(packageId);
            if(speakingPackage.getHadIndustryTypeId()!=null && !speakingPackage.getHadIndustryTypeId().isEmpty()){
                Map<String,String> map = new HashMap();
                map.put("ids", org.apache.tomcat.util.buf.StringUtils.join(speakingPackage.getHadIndustryTypeId(), ','));
                industryTypeBiz.getIndustryTypesList(map)
            }
        }*/
        List<BusinessTypeBase>  businessTypeBases = businessTypeBaseBiz.getAll();
        Map<String,String> businessTypes = new HashMap<String,String>();
        businessTypeBases.forEach(it->{
            businessTypes.put(it.getId(),it.getName());
        });
        model.addAttribute("businessTypes",businessTypes);
        model.addAttribute("packageId",!Utils.isNullString(packageId)&&!"null".equals(packageId)?packageId:"");

        return "page/knowledgeBase/type/queryCommonKnowledgeBase";
    }


    /**
     * 功能描述:转跳到添加页面
     *
     * @param: brotherWinName 打开窗体添加窗体的idx，便于窗体间的交互 ->兄弟窗体
     * @return: java.lang.String
     * @auther:
     * @date: 2018/8/18
     */
    @RequestMapping("addKnowledgeBase")
    public String addKnowledgeBase(Model model,@RequestParam String brotherWinName,String packageId,String affectType) {
        model.addAttribute("knowledgeUsageTypes", KnowledgeUsageType.values());
        model.addAttribute("brotherWinName",brotherWinName);
        model.addAttribute("packageId",packageId);
        model.addAttribute("affectType",AffectType.fromValue(affectType).name());
        return "page/knowledgeBase/addKnowledgeBase";
    }

    /**
     * 保存新增知识库
     *
     * @param knowledgeBaseVo
     * @return
     */
    @PostMapping("/insert")
    @ResponseBody
    public WebResult esInsert(KnowledgeBaseVo knowledgeBaseVo) {

//        return  WebResultUtils.getSuccessCharWebResult("",0,null);
        //调用biz业务层
        return knowledgeBaseBiz.esInsert(knowledgeBaseVo);

    }

    /**
     * 根据字段编辑更新
     *
     * @param knowledgeBaseVo
     * @return
     */
    @RequestMapping("update")
    @ResponseBody
    public WebResult esUpdate(KnowledgeBaseVo knowledgeBaseVo) {

        //调用biz业务层
        return knowledgeBaseBiz.esUpdate(knowledgeBaseVo);

    }

    /**
     * 功能描述:根据ID删除单个用户
     *
     * @param: [id : 需要删除的对象ID]
     * @return: boolean :删除是否成功
     * @auther:
     * @date: 2018/8/6
     */
    @PostMapping("/deleteById")
    @ResponseBody
    public WebResult esDeleteById(String id) {

        //dioa调用biz
        return knowledgeBaseBiz.esDeleteById(id);
    }


    /**
     * 功能描述:根据ID查询查找单个用户
     *
     * @param: [id]
     * @return: KnowledgeBase  将会转为json
     * @auther:
     * @date: 2018/8/6
     */
    @RequestMapping("/selectById")
    @ResponseBody
    public KnowledgeBase selectById(String id) {

        KnowledgeBase knowledgeBase = knowledgeBaseBiz.selectById(id);

        return knowledgeBaseBiz.selectById(id);

    }


    /**
     * 功能描述: 分页查询
     *
     * @param: [
     * key : 查询关键字
     * page :当前页
     * limit:每页大小
     * ]
     * @return: 用于封装layui所需的结果
     * @auther:
     * @date: 2018/8/7
     */
    @RequestMapping("queryKnowledgeBaseBySearch")
    @ResponseBody
    /*public Map<String, Object> queryKnowledgeBaseBySearch(@RequestParam(required = false) String key, Integer page, Integer limit, String packageId, @RequestParam(required = false) String knowledgeType,ModelAndView model) {*/
    public Map<String, Object> queryKnowledgeBaseBySearch(@RequestParam Map<String, String> paramMap, ModelAndView model) {
        //调用biz层
        // return knowledgeBaseBiz.queryKnowledgeBaseBySearch(key, page, limit, packageId,knowledgeType, model);
        return knowledgeBaseBiz.queryKnowledgeBaseBySearch(paramMap, model);
    }


    /**
     * 功能描述: 搜索所有KnowledgeBase,返回json格式字符串
     *
     * @param: []
     * @return: java.util.List<com.hfzy.ihk.facade.linkcall.entity.knowledge.KnowledgeBase>
     * @auther:
     * @date: 2018/8/15
     */
    @RequestMapping("queryAllKnowledgeBase")
    @ResponseBody
    public List<KnowledgeBase> queryAllKnowledgeBase() {

        Page<KnowledgeBase> knowledgeBases = knowledgeBaseBiz.esSearchAllQuestionBase();

        //knowledgeBases.getTotalElements();

        return knowledgeBases.getContent();
    }


    /**
     * 功能描述:返回编辑页面
     *
     * @param: [id] 需要编辑的KnowledgeBase  ID
     * @param refPackageId   关联的packageId ==》用于编辑公共知识库时标识使用
     * @param brotherWinName  关联传值的窗体名
     * @return: java.lang.String  视图
     * @auther:
     * @date: 2018/8/9
     */
    @RequestMapping("editKnowledgeBase")
    public String editKnowledgeBase(String id, Model model,String refPackageId,@RequestParam String brotherWinName,String packageId,String affectType) {

        try {
            //查询出数据
            KnowledgeBase knowledgeBase = knowledgeBaseBiz.selectById(id);


            //将keyworlds和howQuestions和一对一标准答案拼成字符串,放入域中
            String keyworldString = StringUtils.join(knowledgeBase.getKeyworlds(), ",");
            String questionsString = StringUtils.join(knowledgeBase.getHowAskQuestions(), "\n");
            String oneToOneResult = StringUtils.join(knowledgeBase.getOneToOneResult(), ",");

            //存入model
            model.addAttribute("keyworldString", keyworldString);
            model.addAttribute("questionsString", questionsString);
            model.addAttribute("oneToOneResult", oneToOneResult);
            model.addAttribute("knowledgeBaseResultVos", knowledgeBase.getKnowledgeBaseResultVos());
            //查询到所有的所属操作流程
            if (knowledgeBase.getSkipFlowId() != null) {
                //查询流程,放入model
                SpeakingFlow speakingFlow = speakingFlowBiz.selectById(knowledgeBase.getSkipFlowId());

                if (speakingFlow != null) {

                    model.addAttribute("SkipFlowText", speakingFlow.getFlowName());
                }
            }

            //查询所属话术
            if (knowledgeBase.getPackageId() != null) {

                SpeakingPackage speakingPackage = speakingPackageBiz.selectById(knowledgeBase.getPackageId());

                if (speakingPackage != null) {

                    model.addAttribute("packageText", speakingPackage.getPackageName());
                }

            }

            if (knowledgeBase.getMutiSessionFlowId() != null) {
                //查询流程,放入model
                SpeakingFlow speakingFlow = speakingFlowBiz.selectById(knowledgeBase.getMutiSessionFlowId());

                if (speakingFlow != null) {

                    model.addAttribute("MutiSessionFlowText", speakingFlow.getFlowName());

                }

            }

            //将查询对象放进model
            model.addAttribute("editKnowledgeBase", knowledgeBase);
            String selUsageTypes = "";
            if (knowledgeBase.getUsageTypes() != null) {
                for (KnowledgeUsageType knowledgeUsageType : knowledgeBase.getUsageTypes()) {
                    if (selUsageTypes.indexOf(knowledgeUsageType.getValue()) == -1) {
                        selUsageTypes += knowledgeUsageType.getValue() + ",";
                    }
                }
            }
            model.addAttribute("selUsageTypes", selUsageTypes);
            model.addAttribute("knowledgeUsageTypes", KnowledgeUsageType.values());
            model.addAttribute("refPackageId", refPackageId);
            model.addAttribute("brotherWinName", brotherWinName);
            model.addAttribute("packageId", packageId);
            model.addAttribute("affectType",AffectType.fromValue(affectType).name());
        } catch (Exception e) {
            logger.error("转到至编辑页面的查询异常", e);
            return "page/knowledgeBase/error";
        }

        return "page/knowledgeBase/editKnowledgeBase";
    }

    /**
     * 功能描述:用于页面ajax请求的SpeakingFlow
     *
     * @param: []
     * @return: java.util.List<com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingFlow>
     * @auther:
     * @date: 2018/8/16
     */
    @ResponseBody
    @RequestMapping("loadSkipFlow")
    public List<Map<String, String>> loadSkipFlow(String text, String type, String packageId) {
        Map<String, Object> paramMap = new HashMap<>();

        paramMap.put("flowType", type);

        paramMap.put("flowName", text);

        paramMap.put("packageId", packageId);

        List<SpeakingFlow> speakingFlows = speakingFlowBiz.searchFilterSpeakingFlowByField(paramMap);

        //用工具类将数据转化为前台需要的List集合
        List<Map<String, String>> resultList = LayUiParamUtils.getInstance().getJquerySelectParams(speakingFlows, (resultMap, object) -> {
            resultMap.put("label", ((SpeakingFlow) object).getFlowName());
            resultMap.put("value", ((SpeakingFlow) object).getId());
        });

        return resultList;
    }

    /**
     * 功能描述:用于页面ajax请求的查找话术包package
     *
     * @param: []
     * @return: java.util.List<com.hfzy.ihk.facade.linkcall.entity.flow.config.SpeakingFlow>
     * @auther:
     * @date: 2018/8/16
     */
    @ResponseBody
    @RequestMapping("selectPackage")
    public List<Map<String, String>> selectPackage(String text) {

        Map<String, String> paramMap = new HashMap<>();

        paramMap.put("packageName", text);
        paramMap.put("checkStatus", CheckStatus.YES.getValue());

        List<SpeakingPackage> speakingPackageList = speakingPackageBiz.getSpeakingPackageList(paramMap);

        //用工具类将数据转化为前台需要的List集合
        List<Map<String, String>> resultList = LayUiParamUtils.getInstance().getJquerySelectParams(speakingPackageList, (resultMap, object) -> {
            resultMap.put("label", ((SpeakingPackage) object).getPackageName());
            resultMap.put("value", ((SpeakingPackage) object).getId());
        });

        return resultList;
    }

    /**
     * 功能描述:根据所给参数查询(精确查询)
     *
     * @param: []
     * @return: java.util.List<com.hfzy.ihk.facade.linkcall.entity.knowledge.KnowledgeBase>
     * @auther:
     * @date: 2018/8/23
     */
    @RequestMapping("selectByField")
    @ResponseBody
    public WebResult selectByField(@RequestParam Map<String, String> params) {

        WebResult webResult = new WebResult();

        try {
            //调用biz层
            List<KnowledgeBase> list = knowledgeBaseBiz.searchKnowledgeBaseByField(params);
            if (StringUtil.isNotNull(list)) {
                webResult.setTotal(list.size());
                webResult.setRecords(list);
            }
            webResult.setCode(GlobalStatic.CODE_1);
            webResult.setMsg(GlobalStatic.SUCCESS);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("搜索knowledgeBase出错");
            webResult.setCode(GlobalStatic.CODE_0);
            webResult.setMsg(GlobalStatic.FAIL);
            webResult.setTotal(0);
        }

        return webResult;

    }


    /**
     * 功能描述: 接受提交上来的所有问题,然后自动分词,返回到前台
     *
     * @param: Map 有两个参数,一个keywords为当前页面已经存在的关键词,allQuestions为所有问法
     * @return:
     * @auther:oyc
     * @date: 2018/10/12
     */
    @RequestMapping("autoAnalysis")
    @ResponseBody
    public DefaultResult autoAnalysis(@RequestParam Map<String, String> params) {

        DefaultResult result = new DefaultResult();

        List<String> newKeywords = new ArrayList<>();

        try {
            //获取所有的问法
            String[] allQuestions = params.get("allQuestions").split("\n+");

            if (allQuestions != null && allQuestions.length > 0) {

                //用IK分词器分词
                newKeywords = IKSegmenterUtils.getInstance().getKeywords(allQuestions);

                String[] temp = params.get("keywords").split(",");

                if (temp != null && temp.length > 0) {

                    //获取已经添加的关键字
                    List<String> originalKeywords = Arrays.asList(temp);
                    //去重
                    newKeywords.removeAll(originalKeywords);
                }

            }
            result.setCode("1");
            result.setMsg("成功");
            Map<String, Object> resultList = new HashMap<>();
            resultList.put("total", newKeywords.size());
            resultList.put("keywords", newKeywords);
            result.setData(resultList);
        } catch (Exception e) {
            logger.error("自动分词出现错误,赶紧来看看");
            e.printStackTrace();
            result.setCode("0");
            result.setMsg("出现异常");

        }

        return result;
    }


    /**
     * 调用接口查找近义词
     * */
    @RequestMapping("findSameMeanWord")
    @ResponseBody
    public WebResult findSameMeanWord(String keyWord){
        WebResult webResult = null;
        try {
            if(!Utils.isNullString(keyWord)){
                String httpResult  = HttpClientUtils.getMethod(basicFuncUrl+"/synonym/" + keyWord);
                //返回的是json字符串，如：{"synonyms": ["您好", "请问", "吧", "啊", "谢谢", "呀", "呵呵", "吗", "追问", "不过"]}
                JSONObject jsonObject = JSON.parseObject(httpResult);
                if(jsonObject.containsKey("synonyms")){
                    JSONArray jsonArray = (JSONArray)jsonObject.get("synonyms");
                    List<String> list = JSONObject.parseArray(jsonArray.toJSONString(), String.class);
                    if(list!=null && !list.isEmpty()){
                        webResult = WebResultUtils.getSuccessCharWebResult("",list.size(),list);
                    }else{
                        webResult = WebResultUtils.getSuccessCharWebResult("",0,null);
                    }
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            webResult  = WebResultUtils.getExceptionCharWebResult("获取近义词操作异常 "+e.getMessage());
        }finally {
            if(webResult == null)
                webResult  = WebResultUtils.getFailCharWebResult("");
        }
        return webResult;
    }




    /**
     * 检测问法在同一话术包是否已经存在
     *
     * @return
     */
    @RequestMapping("checkTheHowQuestion")
    @ResponseBody
    public WebResult checkTheHowQuestion(KnowledgeBaseVo knowledgeBaseVo) {

        WebResult webResult = new WebResult();

        try {
            List<String> existedHowAskQuestions = knowledgeBaseBiz.checkTheHowQuestion(knowledgeBaseVo);

            webResult.setCode(GlobalStatic.CODE_1);

            webResult.setTotal(existedHowAskQuestions.size());

            webResult.setMsg("查询已存在问法成功");

            webResult.setRecords(existedHowAskQuestions);
        } catch (Exception e) {

            logger.info("查询已存在问法失败", e);

            webResult.setCode(GlobalStatic.CODE_0);

            webResult.setTotal(0);

            webResult.setMsg("查询已存在问法失败");

        }

        return webResult;

    }

    ;

    /**返回当前话术包下所有关键词
     * @return
     */
    @RequestMapping("getAllwords")
    @ResponseBody
    public WebResult getAllwords(@RequestParam Map<String, String> params) {

        WebResult webResult = new WebResult();

        try {

            Set<String> allwords = knowledgeBaseBiz.getAllwords(params);

            webResult.setCode(GlobalStatic.CODE_1);
            webResult.setMsg("查询当前话术包下所有关键词成功");

            if (allwords!=null){
                webResult.setTotal(allwords.size());
                webResult.setParameter(allwords);
            }else {
                webResult.setTotal(0);
                webResult.setParameter(allwords);
            }

        } catch (Exception e) {

            webResult.setCode(GlobalStatic.CODE_0);
            webResult.setMsg("查询当前话术包下所有关键词失败");
            webResult.setTotal(0);
        }

        return webResult;

    }

    /**返回当前话术包下所有问法
     * @return
     */
    @RequestMapping("getAllHowQuestions")
    @ResponseBody
    public WebResult getAllHowQuestions(@RequestParam Map<String, String> params) {

        WebResult webResult = new WebResult();

        try {

            List<String> allHowQuestions = knowledgeBaseBiz.getAllHowQuestions(params);

            webResult.setCode(GlobalStatic.CODE_1);
            webResult.setMsg("查询当前话术包下所有问法成功");

            if (allHowQuestions!=null){
                webResult.setTotal(allHowQuestions.size());
                webResult.setParameter(allHowQuestions);
            }else {
                webResult.setTotal(0);
                webResult.setParameter(allHowQuestions);
            }

        } catch (Exception e) {

            webResult.setCode(GlobalStatic.CODE_0);
            webResult.setMsg("查询当前话术包下所有问法失败");
            webResult.setTotal(0);
        }

        return webResult;

    }


    @Deprecated
    @RequestMapping("aicall/{id}")
    @ResponseBody
    public WebResult aicall(@PathVariable String id) {
        WebResult webResult = new WebResult();
        try {

            String method = HttpClientUtils.getMethod(singleCallUrl+"/knowledgebase/" + id);
            //String method = HttpClientUtils.getMethod("http://172.16.8.172:9999/analysis/knowledgebase/" + id);

            webResult.setMsg("调用python接口成功");
            webResult.setCode(GlobalStatic.CODE_1);
            webResult.setParameter(method);
        } catch (Exception e) {

            webResult.setMsg("调用python接口失败");
            webResult.setCode(GlobalStatic.CODE_0);
            webResult.setParameter(null);

        }

        return webResult;
    }

    ;

    //======================================================华丽分割线============================================

    /**
     * 导入数据去redis
     */
    @RequestMapping("importAllQuestionToRedis")
    @ResponseBody
    public boolean importAllQuestionToRedis(){
        try {

            knowledgeBaseBiz.importAllQuestionToRedis();

        }catch (Exception e){
            return false;
        }

        return true;
    }

    //jquery -ui 需要的数据
  /*  public List<Map<String, String>> getResultList(List<SpeakingFlow> speakingFlows) {
        List<Map<String,String>> resultList=new ArrayList<>();

        if (speakingFlows!=null&&speakingFlows.size()>0) {

            for (SpeakingFlow speakingFlow : speakingFlows) {
                Map<String,String> resultMap=new HashMap<>();
                resultMap.put("label", speakingFlow.getFlowName());
                resultMap.put("value", speakingFlow.getId());
                resultList.add(resultMap);
            }


        }
        return resultList;
    }*/

   /* @RequestMapping("/queryKnowledgeBase")
    public String queryKnowledgeBase(){
        return "page/knowledgeBase/queryKnowledgeBase";
    }

    @RequestMapping("/addKnowledgeBase")
    public String addKnowledgeBase(){
        return "page/knowledgeBase/addKnowledgeBase";
    }

    @RequestMapping("/queryKnowledgeBaseDetail")
    public String queryKnowledgeBaseDetail(){
        return "page/knowledgeBase/queryKnowledgeBaseDetail";
    }*/

    /*@RequestMapping("/addSpeakingFlow")
    @ResponseBody
    public String addSpeakingFlow(){

        SpeakingFlow speakingFlow=new SpeakingFlow();
        speakingFlow.setId(UUIDs.base64UUID());
        speakingFlow.setFlowName("不管这个");

        SpeakingFlow speakingFlow1=new SpeakingFlow();
        speakingFlow1.setId(UUIDs.base64UUID());
        speakingFlow1.setFlowName("加我微信");


        SpeakingFlow speakingFlow2=new SpeakingFlow();
        speakingFlow2.setId(UUIDs.base64UUID());
        speakingFlow2.setFlowName("当面聊");


        SpeakingFlow speakingFlow4=new SpeakingFlow();
        speakingFlow4.setId(UUIDs.base64UUID());
        speakingFlow4.setFlowName("有空去看");


        SpeakingFlow speakingFlow5=new SpeakingFlow();
        speakingFlow5.setId(UUIDs.base64UUID());
        speakingFlow5.setFlowName("朋友可能需要");

        SpeakingFlow speakingFlow6=new SpeakingFlow();
        speakingFlow6.setId(UUIDs.base64UUID());
        speakingFlow6.setFlowName("新来的");

        List<SpeakingFlow> peakingFlowList =new ArrayList<>();

        peakingFlowList.add(speakingFlow);
        peakingFlowList.add(speakingFlow1);
        peakingFlowList.add(speakingFlow2);
        peakingFlowList.add(speakingFlow4);
        peakingFlowList.add(speakingFlow5);
        peakingFlowList.add(speakingFlow6);

        repository.saveAll(peakingFlowList);

        return "搞鸡儿OK";
    };

    @Autowired
    private SpeakingFlowRepository repository;*/

    /**
     * 导入知识库
     * */
    @ResponseBody
    @RequestMapping("importKnowledgeBase")
    public WebResult importKnowledgeBase(@RequestParam MultipartFile file,String packageId){
        WebResult webResult = new WebResult();
        try {
            if(Utils.isNullString(packageId)){
                return WebResultUtils.getFailCharWebResult("操作失败，没有指定对应的知识库类型");
            }
            /*Set<String> members = redisTemplate.opsForSet().members(packageId);
            Iterator it1 = members.iterator();
            while(it1.hasNext()){
                redisTemplate.opsForSet().remove(packageId, it1.next());
            }*/
            //获取文件名后缀
            String suffix  = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);

            importByFile(file.getInputStream(),packageId,suffix);
           /* //用来存储 最后的知识库标题和内容
            String currentTitle = "";
            String keywords = "";
            List<String> keywordList = new ArrayList<String>();//用于记 keyword的顺序问题
            LinkedList<String> answers = new LinkedList<String>();
            Set<String> titles = new HashSet<String>();
            List<String> titleList = new ArrayList<String>();//用于记 title的顺序问题
            List<KnowledgeBase> knowledgeBaseList = new ArrayList<>();
            List<KnowledgeUsageType> usageTypes = new ArrayList<KnowledgeUsageType>();
            usageTypes.add(KnowledgeUsageType.AICALL);
            usageTypes.add(KnowledgeUsageType.NORMALCALL);


            if("csv".equals(suffix)){
                List<String[]> list = Utils.readCsv(file.getInputStream());
                for(String[] array:list){
                    if(array==null || array.length<3){
                        continue;
                    }
                    String question = array[0];
                    keywords = array[1];
                    String answer = array[2];
                    //标题是有重复的 === 处理方式 如果添加到set集合是成功的，同时对应的答案是非空情况下，择添加到需要写入的知识库集合中
                    String title = StringUtil.stringFilter(question);
                    if(titles.add(title)){
                        currentTitle = title;
                        String lastTitle = title;
                        String lastKeyword = keywords;
                        if(titleList!=null && !titleList.isEmpty()){
                            lastTitle = titleList.get(titleList.size()-1);//取 最后一个元素
                        }
                        if(keywordList!=null && !keywordList.isEmpty()){
                            lastKeyword = keywordList.get(keywordList.size()-1);//取 最后一个元素
                        }
                        keywordList.add(keywords);
                        titleList.add(title);
                        if(answers!=null && !answers.isEmpty() && !Utils.isNullString(lastTitle)){
                            knowledgeBaseList.add(getKnowledgeBase(lastTitle,answers,packageId,usageTypes,lastKeyword));
                        }
                        //保存后，进入到下一个知识库，清空回答
                        answers = new LinkedList<String>();
                    }
                    answers.add(answer);
                }
                if(!Utils.isNullString(currentTitle) && !Utils.isNullString(keywords) && answers!=null && !answers.isEmpty()){
                    knowledgeBaseList.add(getKnowledgeBase(currentTitle,answers,packageId,usageTypes,keywords));
                }
            }else{
                Workbook workbook = ExcelUtils.getExcelWorkbook(file.getInputStream());
                List<Sheet> sheetList = ExcelUtils.getSheetListByWorkbook(workbook);

                for (Sheet sheet : sheetList) {
                    List<Row> rowList = ExcelUtils.getRowListBySheet(sheet);
                    if (rowList != null && !rowList.isEmpty()) {
                        rowList.remove(0);////去除第一行（文字标题行）
                        for (Row row : rowList) {
                            Cell questionCell = row.getCell(0);
                            Cell keyWordCell = row.getCell(1);
                            Cell answerCell = row.getCell(2);
                            questionCell.setCellType(1);
                            answerCell.setCellType(1);
                            keyWordCell.setCellType(1);
                            //标题是有重复的 === 处理方式 如果添加到set集合是成功的，同时对应的答案是非空情况下，择添加到需要写入的知识库集合中
                            String title = StringUtil.stringFilter(questionCell.getStringCellValue());
                            keywords = keyWordCell.getStringCellValue();
                            if(titles.add(title)){
                                currentTitle = title;
                                String lastTitle = title;
                                if(titleList!=null && !titleList.isEmpty()){
                                    lastTitle = titleList.get(titleList.size()-1);//取 最后一个元素
                                }
                                titleList.add(title);
                                if(answers!=null && !answers.isEmpty()){
                                    knowledgeBaseList.add(getKnowledgeBase(lastTitle,answers,packageId,usageTypes,keywords));
                                }
                                //保存后，进入到下一个知识库，清空回答
                                answers = new LinkedList<String>();
                            }
                            answers.add(answerCell.getStringCellValue());
                        }
                    }
                }
                if(!Utils.isNullString(currentTitle) && !Utils.isNullString(keywords) && answers!=null && !answers.isEmpty()){
                    knowledgeBaseList.add(getKnowledgeBase(currentTitle,answers,packageId,usageTypes,keywords));
                }
            }
            knowledgeBaseBiz.addKnowledgeBases(titleList,knowledgeBaseList);*/
            webResult.setTotal(0);
            webResult.setMsg(GlobalStatic.SUCCESS);
            webResult.setCode(GlobalStatic.CODE_1);
            webResult.setRecords(null);
        } catch (IOException e) {
            webResult.setMsg("读取文件异常");
            webResult.setCode(GlobalStatic.CODE_N2);
            webResult.setTotal(0);
            webResult.setRecords(null);
        } catch (Exception e) {
            e.printStackTrace();
            webResult.setMsg(GlobalStatic.EXCEPTION_CHAR);
            webResult.setCode(GlobalStatic.CODE_N);
            webResult.setTotal(0);
            webResult.setRecords(null);
        }
        return webResult;
    }

    private int importByFile(InputStream inputStream, String packageId, String suffix) throws IOException {
        int count = 0;
        //用来存储 最后的知识库标题和内容
        String currentTitle = "";
        String keywords = "";
        List<String> keywordList = new ArrayList<String>();//用于记 keyword的顺序问题
        LinkedList<String> answers = new LinkedList<String>();
        LinkedList<String> questions = new LinkedList<String>();
        Set<String> titles = new HashSet<String>();
        List<String> titleList = new ArrayList<String>();//用于记 title的顺序问题
        List<KnowledgeBase> knowledgeBaseList = new ArrayList<>();
        List<KnowledgeUsageType> usageTypes = new ArrayList<KnowledgeUsageType>();
        usageTypes.add(KnowledgeUsageType.AICALL);
        usageTypes.add(KnowledgeUsageType.NORMALCALL);


        if ("csv".equals(suffix)) {
            List<String[]> list = Utils.readCsv(inputStream);
            for (String[] array : list) {
                if (array == null || array.length < 3) {
                    continue;
                }
                String question = array[0];
                keywords = array[1];
                String answer = array[2];
                //标题是有重复的 === 处理方式 如果添加到set集合是成功的，同时对应的答案是非空情况下，择添加到需要写入的知识库集合中
                String title = StringUtil.stringFilter(question);
                if (titles.add(title)) {
                    currentTitle = title;
                    String lastTitle = title;

                    if (titleList != null && !titleList.isEmpty()) {
                        lastTitle = titleList.get(titleList.size() - 1);//取 最后一个元素
                    }

                    keywordList.add(keywords);
                    titleList.add(title);
                    if (answers != null && !answers.isEmpty() && !Utils.isNullString(lastTitle)) {
                        knowledgeBaseList.add(getKnowledgeBase(lastTitle, answers, packageId, usageTypes, keywords));
                    }
                    //保存后，进入到下一个知识库，清空回答
                    answers = new LinkedList<String>();
                    keywords = "";//清空关键词
                }
                keywords += "，"+keywords;
                answers.add(answer);
            }
            if (!Utils.isNullString(currentTitle) && !Utils.isNullString(keywords) && answers != null && !answers.isEmpty()) {
                knowledgeBaseList.add(getKnowledgeBase(currentTitle, answers, packageId, usageTypes, keywords));
            }
        } else {
            Workbook workbook = ExcelUtils.getExcelWorkbook(inputStream);
            List<Sheet> sheetList = ExcelUtils.getSheetListByWorkbook(workbook);
            Set<String>  answerSet = new HashSet<>();
            Set<String>  questionSet = new HashSet<>();
            for (Sheet sheet : sheetList) {
                List<Row> rowList = ExcelUtils.getRowListBySheet(sheet);
                if (rowList != null && !rowList.isEmpty()) {
                    rowList.remove(0);////去除第一行（文字标题行）
                    for (Row row : rowList) {
                        Cell titleCell = row.getCell(0);
                        Cell keyWordCell = row.getCell(1);
                        Cell answerCell = row.getCell(2);
                        Cell questionCell = row.getCell(3);
                        titleCell.setCellType(1);
                        answerCell.setCellType(1);
                        keyWordCell.setCellType(1);
                        questionCell.setCellType(1);
                        //标题是有重复的 === 处理方式 如果添加到set集合是成功的，同时对应的答案是非空情况下，择添加到需要写入的知识库集合中
                        String title = StringUtil.stringFilter(titleCell.getStringCellValue());
                        if (titles.add(title)) {
                            currentTitle = title;
                            String lastTitle = title;
                            if (titleList != null && !titleList.isEmpty()) {
                                lastTitle = titleList.get(titleList.size() - 1);//取 最后一个元素
                            }
                            titleList.add(title);
                            if (answers != null && !answers.isEmpty()) {
                                knowledgeBaseList.add(getKnowledgeBase(lastTitle, answers, packageId, usageTypes, keywords,questions));
                            }
                            //保存后，进入到下一个知识库，清空回答
                            answers = new LinkedList<String>();
                            questions = new LinkedList<String>();
                            keywords = "";//清空关键词
                            answerSet = new HashSet<>();
                            questionSet = new HashSet<>();
                        }
                        keywords += "，"+keyWordCell.getStringCellValue();
                        if(!Utils.isNullString(answerCell.getStringCellValue()) && answerSet.add(StringUtil.stringFilter(answerCell.getStringCellValue()))){
                            answers.add(answerCell.getStringCellValue());
                        }

                        if(!Utils.isNullString(questionCell.getStringCellValue()) && questionSet.add(StringUtil.stringFilter(questionCell.getStringCellValue())))
                            questions.add(questionCell.getStringCellValue());
                    }
                }
            }
            if (!Utils.isNullString(currentTitle) && !Utils.isNullString(keywords) && answers != null && !answers.isEmpty()) {
                knowledgeBaseList.add(getKnowledgeBase(currentTitle, answers, packageId, usageTypes, keywords,questions));
            }
        }
        knowledgeBaseBiz.addKnowledgeBases(titleList, knowledgeBaseList);
        return count;
    }

    @ResponseBody
    @RequestMapping("imports")
    public void imports(String packageId){
        try {
            int i = 0;
            while (i<=100){
                File file = new File("F:\\tool\\jiwu_all_data5\\jiwu_all_data\\jiwu_segment_"+i+".csv");
                FileInputStream fis = new FileInputStream(file);
                importByFile(fis,packageId,"csv");
                i++;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private KnowledgeBase getKnowledgeBase(String lastTitle,LinkedList<String> answers,String packageId,List<KnowledgeUsageType> usageTypes,String keywords){
        KnowledgeBase knowledgeBase = new KnowledgeBase();
        knowledgeBase.setAnswerType(AnswerType.ONE_TO_ONE);
        knowledgeBase.setActionCodeBreak(true);
        knowledgeBase.setAffectType(AffectType.COMMON);
        knowledgeBase.setAfterAnswerOptionalType(AfterAnswerOptionalType.WAIT_CUSTOMER_ANSWER);
        knowledgeBase.setHowAskQuestions(Arrays.asList(lastTitle));
        knowledgeBase.setKnowledgeType(KnowledgeType.COMMON);
        knowledgeBase.setPackageId(packageId);
        knowledgeBase.setTitle(lastTitle);
        knowledgeBase.setUsageTypes(usageTypes);
        knowledgeBase.setOneToOneResult(answers);
        if(!Utils.isNullString(keywords)){
            List<String> keyWordList = Arrays.asList(keywords.split("，"));
            knowledgeBase.setKeyworlds(keyWordList.stream().distinct().filter(s -> {
                return StringUtil.isNotNull(s);
            }).collect(toList()));
        }else{
            knowledgeBase.setKeyworlds(new ArrayList<>());
        }
        return knowledgeBase;
    }


    private KnowledgeBase getKnowledgeBase(String lastTitle,LinkedList<String> answers,String packageId,List<KnowledgeUsageType> usageTypes,String keywords,List<String> questions){
        if(questions==null || questions.isEmpty()){
           return getKnowledgeBase(lastTitle,answers,packageId,usageTypes,keywords);
        }
//        Set<String> members = redisTemplate.opsForSet().members(packageId);
        KnowledgeBase knowledgeBase = new KnowledgeBase();
        knowledgeBase.setAnswerType(AnswerType.ONE_TO_ONE);
        knowledgeBase.setActionCodeBreak(true);
        knowledgeBase.setAffectType(AffectType.COMMON);
        knowledgeBase.setAfterAnswerOptionalType(AfterAnswerOptionalType.WAIT_CUSTOMER_ANSWER);
        knowledgeBase.setHowAskQuestions(questions);
        knowledgeBase.setKnowledgeType(KnowledgeType.COMMON);
        knowledgeBase.setPackageId(packageId);
        knowledgeBase.setTitle(lastTitle);
        knowledgeBase.setUsageTypes(usageTypes);
        knowledgeBase.setOneToOneResult(answers);
        if(!Utils.isNullString(keywords)){
            List<String> keyWordList = Arrays.asList(keywords.split("，"));
            knowledgeBase.setKeyworlds(keyWordList.stream().distinct().filter(s -> {
                return StringUtil.isNotNull(s);
            }).collect(toList()));
        }else{
            knowledgeBase.setKeyworlds(new ArrayList<>());
        }
        return knowledgeBase;
    }


    @ResponseBody
    @RequestMapping("export")
    public void export(@RequestParam Map<String, String> paramMap, ModelAndView model,HttpServletResponse response) {
        logger.info("导出知识库结果集"+ StringUtils.join(paramMap.entrySet(),","));
        try{
            paramMap.put("limit","1000");
            paramMap.put("page","1");
            //调用biz层
            Map<String, Object> result = knowledgeBaseBiz.queryKnowledgeBaseBySearch(paramMap, model);
            if(result!=null && result.containsKey("count") && (long)result.get("count")>0){
                String fileName = Utils.date2String(new Date(),Utils.DATE_FORMAT_DATETIME_2)+"知识库导出数据.xls";
                response.reset();
                response.setContentType("application/vnd.ms-excel;charset=utf-8");//xls
                response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8"));
                OutputStream outputStream = null;
                List<KnowledgeBase>  list = (List<KnowledgeBase>)result.get("data");
                List<Map> dataList = new ArrayList<Map>();
                list.forEach(it->{
                    List<String>  askQuestions = it.getHowAskQuestions()!=null?it.getHowAskQuestions():new ArrayList<>();
                    List<String> oneToOneResults = it.getOneToOneResult()!=null?it.getOneToOneResult():new ArrayList<>();
                    List<Map> maps = new ArrayList<>();
                    int size = oneToOneResults.size()>askQuestions.size()?oneToOneResults.size():askQuestions.size();
                    for (int i=0;i<size;i++){
                        LinkedHashMap map = new LinkedHashMap();
                        map.put("标题",it.getTitle());
                        map.put("关键词",StringUtils.join(it.getKeyworlds(),"，"));

                        if(i<oneToOneResults.size()){
                            map.put("答法",oneToOneResults.get(i));
                        }else{
                            if(oneToOneResults.size()>0){
                                map.put("答法",oneToOneResults.get(oneToOneResults.size()-1));
                            }else
                                map.put("答法","");
                        }

                        if(i<askQuestions.size()){
                            map.put("问法",askQuestions.get(i));
                        }else{
                            if(askQuestions.size()>0)
                                map.put("问法",askQuestions.get(askQuestions.size()-1));
                            else
                                map.put("问法","");
                        }
                        dataList.add(map);
                    }
                });
                Workbook workbook = ExcelUtils.generate("知识库导出数据",dataList);
                outputStream = response.getOutputStream();
                workbook.write(response.getOutputStream());
                outputStream.flush();
                outputStream.close();
            }
        }catch (Exception e){
            logger.info("导出知识库结果集 异常 "+ e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * @param id                 知识库的id
     * @param resultId          录音文件id
     * @param recordFileUrl    录音文件
     * */
    @ResponseBody
    @RequestMapping("updateKnowledgeBaseResultVo")
    public WebResult updateKnowledgeBaseResultVo(String id,String resultId,String recordFileUrl){
        WebResult webResult = new WebResult();
        try{
            KnowledgeBase knowledgeBase = selectById(id);
            List<KnowledgeBaseResultVo> knowledgeBaseResultVos = knowledgeBase.getKnowledgeBaseResultVos();
            knowledgeBaseResultVos.forEach(it->{
                if(resultId.equals(it.getId())){
                    it.setRecordFileUrl(recordFileUrl);
                }
            });
            knowledgeBase.setKnowledgeBaseResultVos(knowledgeBaseResultVos);
            //过滤没有录音文件的集合
            knowledgeBaseResultVos = knowledgeBaseResultVos.stream().filter(it->Utils.isNullString(it.getRecordFileUrl())).collect(Collectors.toList());
            //如果不存在时===> 则说明录音上传成功
            if(knowledgeBaseResultVos==null || knowledgeBaseResultVos.isEmpty()){
                knowledgeBase.setHadUploadFile(true);
            }
            knowledgeBaseBiz.update(knowledgeBase);
            webResult.setCode(GlobalStatic.CODE_1);
            webResult.setMsg(GlobalStatic.SUCCESS);
        }catch (Exception e){
            webResult.setMsg(GlobalStatic.EXCEPTION_CHAR);
            webResult.setCode(GlobalStatic.CODE_N);
        }
        return webResult;
    }






}
